package com.lepu.app.fun.health.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.BitmapLoadUtil;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MarkerOptions.MarkerAnimateType;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UmengHelper;
import com.lepu.app.fun.health.adapter.ListAdapter;
import com.lepu.app.fun.health.bean.BeanDurg;
import com.lepu.app.fun.health.bean.BeanDurg.DurgStore;
import com.lepu.app.fun.health.bean.BeanDurg.TopDurg;
import com.lepu.app.fun.health.bean.BeanMyAddress;
import com.lepu.app.main.activity.AppBroswerActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

@SuppressLint("InflateParams")
public class MapActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,AsyncRequest{
	private static final String REQUEST_DATA = "request_data";
	
	// 定位相关
	private LocationClient mLocClient;
	private MyLocationListenner myListener = new MyLocationListenner();
    private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
	
    private boolean isFirstLoc = true; // 是否首次定位
   
    //MapView 是地图主控件
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    
    //地图上的坐标图
    private BitmapDescriptor mapMark = BitmapDescriptorFactory.fromResource(R.drawable.map_mark_icon);
    private ArrayList<Marker> marketList = new ArrayList<Marker>();
    private InfoWindow mInfoWindow;
	
	public BeanMyAddress mBeanMyAddress = new BeanMyAddress(); //我的位置
	
    private ListView mListView;
    private View mHeadView = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.health_map_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		UmengHelper.onResume(this, UmengEvent.page_xunyiwenyao);
	}

	@Override
	public void onPause() {
		super.onPause();

		UmengHelper.onPause(this, UmengEvent.page_xunyiwenyao);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		Intent intent = new Intent(MapActivity.this, AppBroswerActivity.class);
		intent.putExtra("title", "服务介绍");
		intent.putExtra("url", "http://dl.ixinzang.com/pasm/saleMedicine/index.html");
		startActivity(intent,true);
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle(R.string.health_title_yuan_cheng_hui_zhen);
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);
		topbar.setRightText("服务介绍");
		
		mListView = (ListView) findViewById(R.id.listView);
		
		mMapView = (MapView) findViewById(R.id.mapView);
		mBaiduMap = mMapView.getMap();
		
		// 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		//option.setScanSpan(60000); //一分钟定位一次
		option.setAddrType("all"); //获取string 地址 4.0之前
		option.setIsNeedAddress(true); //获取string 地址4.0之后

		mLocClient.setLocOption(option);
		mLocClient.start();
        //设置定位样式
        mCurrentMode = LocationMode.FOLLOWING;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
        
	}
	
	
    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                     //此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                //设置地图中心点以及缩放尺度
                builder.target(ll).zoom(13.5f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                
                mBeanMyAddress.Address = location.getAddrStr();
                mBeanMyAddress.City = location.getCity();
                mBeanMyAddress.Latitude = ll.latitude;
                mBeanMyAddress.Longitude = ll.longitude;
                
                request(ll);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    //添加地图上的覆盖物
	public void addOverLay(LatLng latLng){
		MarkerOptions ooA = new MarkerOptions().position(latLng).icon(mapMark).zIndex(9).draggable(true);
        // 掉下动画
        ooA.animateType(MarkerAnimateType.drop);
        Marker marker = (Marker) mBaiduMap.addOverlay(ooA);
        marketList.add(marker);
	}
	
	public void initListData(final BeanDurg beanDurg){
		if(mHeadView != null){
			mListView.removeHeaderView(mHeadView);
		}
		
		mHeadView = LayoutInflater.from(MapActivity.this).inflate(R.layout.map_list_head, null);
		TextView durgCount = (TextView) mHeadView.findViewById(R.id.durgCount);
		LinearLayout durgLayout1 = (LinearLayout) mHeadView.findViewById(R.id.durgLayout1);
		LinearLayout durgLayout2 = (LinearLayout) mHeadView.findViewById(R.id.durgLayout2);
		LinearLayout durgLayout3 = (LinearLayout) mHeadView.findViewById(R.id.durgLayout3);
		
		ImageView durgImage1 = (ImageView) mHeadView.findViewById(R.id.durgImage1);
		ImageView durgImage2 = (ImageView) mHeadView.findViewById(R.id.durgImage2);
		ImageView durgImage3 = (ImageView) mHeadView.findViewById(R.id.durgImage3);
		
		TextView durgName1 = (TextView) mHeadView.findViewById(R.id.durgName1);
		TextView durgName2 = (TextView) mHeadView.findViewById(R.id.durgName2);
		TextView durgName3 = (TextView) mHeadView.findViewById(R.id.durgName3);
		
		TextView durgPrice1 = (TextView) mHeadView.findViewById(R.id.durgPrice1);
		TextView durgPrice2 = (TextView) mHeadView.findViewById(R.id.durgPrice2);
		TextView durgPrice3 = (TextView) mHeadView.findViewById(R.id.durgPrice3);
		
		TextView moreText = (TextView) mHeadView.findViewById(R.id.more);
		
		//药品信息
		if(beanDurg.OnLineMedicineList != null){
			
			for(int i=0; i<beanDurg.OnLineMedicineList.size(); i++){
				TopDurg durg = beanDurg.OnLineMedicineList.get(i);
				
				if(durg.ImgUrl != null){
					durg.ImgUrls = (List<String>) Arrays.asList(durg.ImgUrl.split("\\|"));
				}
				if(i == 0){
					durgLayout1.setVisibility(View.VISIBLE);
					durgName1.setText(durg.GenericName);
					durgPrice1.setText("￥ "+durg.Price);
					
                    if(durg.ImgUrls != null){
                    	BitmapLoadUtil.displayImage(R.drawable.default_icon_small,durg.ImgUrls.get(0),durgImage1);
					}
					
                    durgLayout1.setOnClickListener(new ViewClick(durg.MedicineID));
				}
				
				if(i == 1){
					durgLayout2.setVisibility(View.VISIBLE);
					durgName2.setText(durg.GenericName);
					durgPrice2.setText("￥ "+durg.Price);
					
                    if(durg.ImgUrls != null){
                    	BitmapLoadUtil.displayImage(R.drawable.default_icon_small,durg.ImgUrls.get(0),durgImage2);
					}
                    
                    durgLayout2.setOnClickListener(new ViewClick(durg.MedicineID));
				}
				
				if(i == 2){
					durgLayout3.setVisibility(View.VISIBLE);
					durgName3.setText(durg.GenericName);
					durgPrice3.setText("￥ "+durg.Price);
					
					if(durg.ImgUrls != null){
						BitmapLoadUtil.displayImage(R.drawable.default_icon_small,durg.ImgUrls.get(0),durgImage3);
					}
					
					durgLayout3.setOnClickListener(new ViewClick(durg.MedicineID));
				}
			}
		}
		
		//更多产品
		moreText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(MapActivity.this, MoreDurgActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("MedicineList", beanDurg.OnLineMedicineList);
				intent.putExtras(bundle);
				startActivity(intent,true);
			}
		});
		
		//count
		if(beanDurg.ListInfo != null && beanDurg.ListInfo.size() > 0){
			durgCount.setText("在您附近有"+beanDurg.ListInfo.size()+"个药店/诊所");
		}else{
			durgCount.setText("附近没有搜索到您所需的药店/诊所");
		}
		
		//listView
		mListView.addHeaderView(mHeadView);
		ListAdapter adapter = new ListAdapter(MapActivity.this,beanDurg.ListInfo, mBeanMyAddress);
		mListView.setAdapter(adapter);
	}
	
	public class ViewClick implements View.OnClickListener{

		String durgId="";
		public ViewClick(String durgId){
			this.durgId = durgId;
		}
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.durgLayout1:
				Intent intent1 = new Intent(MapActivity.this,DurgDetailActivity.class);
				Bundle bundle1 = new Bundle();
				bundle1.putSerializable("durgId", durgId);
				intent1.putExtras(bundle1);
				startActivity(intent1,true);
				break;
			case R.id.durgLayout2:
				Intent intent2 = new Intent(MapActivity.this,DurgDetailActivity.class);
				Bundle bundle2 = new Bundle();
				bundle2.putSerializable("durgId", durgId);
				intent2.putExtras(bundle2);
				startActivity(intent2,true);
				break;
			case R.id.durgLayout3:
				Intent intent3 = new Intent(MapActivity.this,DurgDetailActivity.class);
				Bundle bundle3 = new Bundle();
				bundle3.putSerializable("durgId", durgId);
				intent3.putExtras(bundle3);
				startActivity(intent3,true);
				break;

			default:
				break;
			}
		}
		
	}
	
	/**
	 * 请求消息
	 */
	private void request(LatLng latLng) {
		String url = Setting.getHealthDurgDataUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
		    params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("Latitude", latLng.latitude);
			params.put("Longitude", latLng.longitude);
		} catch (Exception e) {
			
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_DATA, true);
	}

	//
	int index = 0;
	
	@Override
	public void RequestComplete(Object object, Object data) {
		BeanDurg beanDurg = BeanDurg.parseJsonData((String) data);
		
		if(beanDurg.ListInfo == null)
			return;
		
		//添加地图覆盖物
		final ArrayList<DurgStore> storeList = beanDurg.ListInfo;
		for(int i=0; i<storeList.size(); i++){
			LatLng latlng = new LatLng(storeList.get(i).Latitude,storeList.get(i).Longitude);
			addOverLay(latlng);
			
		}
		
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
	            public boolean onMarkerClick(final Marker marker) {
	                Button button = new Button(getApplicationContext());
	                button.setBackgroundResource(R.drawable.popup);
	                button.setTextColor(getResources().getColor(R.color.color_text_black));
	                
	                for(int i=0; i<storeList.size(); i++){
	                	index = i;
	                	if(marker == marketList.get(i)){
	                		button.setText(storeList.get(i).InstitutionName);
	                		button.setOnClickListener(new OnClickListener() {
		                        public void onClick(View v) {
		                        	Intent intent = new Intent(MapActivity.this,RouteActivity.class);
		            				
		            				Bundle bundle1 = new Bundle();
		            				bundle1.putSerializable("durgStore", storeList.get(index));
		            				intent.putExtras(bundle1);
		            				
		            				Bundle bundle2 = new Bundle();
		            				bundle2.putSerializable("myAddress", mBeanMyAddress);
		            				intent.putExtras(bundle2);
		            				startActivity(intent,true);
		                            
		                        }
		                    });
	                		
	                		LatLng ll = marker.getPosition();
		                    mInfoWindow = new InfoWindow(button, ll, -47);
		                    mBaiduMap.showInfoWindow(mInfoWindow);
	                	}
	                }
	                
	                return true;
	            }
	        });
		
		initListData(beanDurg);
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		
	}


}
